// 保存图片到手机
export function onSaveToPhone(image) {
    return new Promise((resolve, reject) => {
		getSetting().then((res) => {
			// 判断用户是否授权了保存到本地的权限
			if (!res.authSetting['scope.writePhotosAlbum']) {
				authorize().then(() => {
					saveImageToPhotosAlbum(image).then(() => {
						resolve() 
					})
				}).catch(() => {
					showModal(image).then(() => {
						resolve() 
					})
				})
			} else {
				saveImageToPhotosAlbum(image).then(() => {
					resolve() 
				})
			}
		})
    })
};
//打开设置，引导用户授权
export function onOpenSetting(image) {
    return new Promise((resolve, reject) => {
		wx.openSetting({
			success: (res) => {
				if (res.authSetting['scope.writePhotosAlbum']) {
					onSaveToPhone(image).then(() => {// 接受授权后保存图片
						resolve() 
					})
				}
			}
		})
    })
};
// 获取用户已经授予了哪些权限
export function getSetting() {
    return new Promise((resolve, reject) => {
		wx.getSetting({
			success: res => {
				resolve(res)
			}
		})
    })
};
// 发起首次授权请求
export function authorize() {
    return new Promise((resolve, reject) => {
		wx.authorize({
			scope: 'scope.writePhotosAlbum',
			success: () => {
				resolve()
			},
			fail: res => { //这里是用户拒绝授权后的回调
				reject()
			}
		})
    })
};
// 保存图片到系统相册
export function saveImageToPhotosAlbum(saveUrl) {
    return new Promise((resolve, reject) => {
		wx.saveImageToPhotosAlbum({
			filePath: saveUrl,
			success: (res) => {
				wx.showToast({
					title: '保存成功',
					duration: 1000,
				})
				resolve()
			}
		})
    })
};
// 弹出模态框提示用户是否要去设置页授权
export function showModal(image) {
    return new Promise((resolve, reject) => {
		wx.showModal({
			title: '检测到您没有打开保存到相册的权限，是否前往设置打开？',
			success: (res) => {
				if (res.confirm) {
					onOpenSetting(image).then(() => {// 打开设置页面
						resolve() 
					})      
				}
			}
		})
    })
};